import { app, BrowserWindow, ipcMain, Tray, nativeImage, Menu } from 'electron'
import path from "path"
import fs from "fs"
import Store from 'electron-store'
import "./setting/buildMenu.js"
const store = new Store()
export let mainWin = null
let tray = null
// 动态注册ipc事件
async function registerIpcHandlers() {
  const __dirname = path.resolve();
  const handlersDir = path.join(__dirname, './electron/ipcHandlers'); // 处理目录路径
  const files = fs.readdirSync(handlersDir).filter(file => file.endsWith('.js')); // 读取目录下的 .js 文件
  await Promise.all(
    files.map(async (file) => {
      // const handlerName = file.replace('.js', ''); // 事件名
      const modulePath = path.join(handlersDir, file);
      const handlerModule = await import(`file://${modulePath}`); // ESM 方式导入
      Object.keys(handlerModule).forEach(v => {
        const fn = handlerModule[v]
        typeof fn === 'function' && ipcMain.handle(v, fn)
      })
    })
  );
}
// 创建窗口
export function createWindow() {
  const windowState = store.get('windowState', { width: 1000, height: 600 });
  const {width, height, x, y} = windowState
  // console.log(windowState)
  mainWin = new BrowserWindow({
    width, height, x, y,
    show: false,
    webPreferences: {
      preload: path.resolve(path.resolve(), './preload/index.js')
    }
  })
}
// 注册事件
export function addEvent(){
  app.on('activate', () => {
    if(BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });
  app.on('before-quit', () => {
    if (tray) { 
      tray.destroy(); // 销毁托盘图标
    }
  })
  // 加载本地开发服务器的 URL
  mainWin.loadURL('http://localhost:3000');
  mainWin.on('resize', () => {
    const { width, height } = mainWin.getBounds();
    store.set('windowState', { ...store.get('windowState'), width, height })
  })
  mainWin.on('move', () => {
    const { x, y } = mainWin.getBounds();
    store.set('windowState', { ...store.get('windowState'), x, y })
  })
  // 监听资源加载到位，再去打开窗口
  mainWin.on('ready-to-show', () => {
    mainWin.show()
    mainWin.webContents.openDevTools() // 临时打开开发者工具
  })
  mainWin.on('close', (event) => {
    event.preventDefault(); // 阻止窗口关闭
    mainWin.hide(); // 隐藏窗口
    tray && tray.setToolTip('应用已最小化到托盘'); // 设置托盘提示文字
  });
  registerIpcHandlers()
}
// 设置托盘图标、右击菜单、左击事件
function createTray(){
  const icon = nativeImage.createFromPath(path.resolve(path.resolve(), './electron/assets/URL.png'))
  tray = new Tray(icon)
  tray.setToolTip('saveurl')
  const contextMenu = Menu.buildFromTemplate([
    { 
      label: '退出', click: () => {
        closeWinAndTray()
      }
    },
  ])
  tray.setContextMenu(contextMenu)
  tray.on('click', e => {
    // console.log(e)
    // console.log(app)
    if(e.shiftKey) {
      closeWinAndTray()
    } else {
      mainWin.show()
    }
  })
}
function closeWinAndTray(){
  tray.destroy();  // 销毁托盘图标
  tray = null
  app.quit()
}
// 项目流程
app.whenReady().then(() => {
  createWindow()
  createTray()
  addEvent()
});